﻿using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Reflection;
using Microsoft.WindowsMobile.PocketOutlook;
using Microsoft.WindowsMobile.Forms;
using System.Drawing;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace SMSTasker
{
    public partial class fmSender : Form
    {
        private Point scales;
        private List<Task> m_Tasks;
        private List<String> cachedTasks;
        private String ContactName;
        private String ContactPhone;
        private int cachedTasksLimit = 10;

        public fmSender()
        {
            InitializeComponent();
            scales = new Point(((int)this.CurrentAutoScaleDimensions.Width) / 96, ((int)this.CurrentAutoScaleDimensions.Height) / 96);
            m_Tasks = new List<Task>();
            cachedTasks = new List<String>();
            Localize();
        }

        private void Localize()
        {
            menuItem3.Text = Localizer.Instance.GetString("fmSender.Tasks");
            menuItem1.Text = Localizer.Instance.GetString("fmSender.Add");
            menuItem4.Text = Localizer.Instance.GetString("fmSender.Cancel");
            menuItem2.Text = Localizer.Instance.GetString("fmSender.Send");
            label3.Text = Localizer.Instance.GetString("fmSender.TasksToSend");
            lbReciever.Text = Localizer.Instance.GetString("fmSender.Receiver");
            label4.Text = Localizer.Instance.GetString("fmSender.CharCount");
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            fmTask ftask = new fmTask();
            foreach (String str in cachedTasks)
	        {
                ftask.cbTasks.Items.Add(str);
	        }
            if(ftask.ShowDialog() == DialogResult.OK)
            {
                if (ftask.edTask.Text.Length == 0)
                {
                    return;
                }
                Task tsk = new Task(ftask.edTask.Text, ftask.cbPriority.Checked, ftask.cbDays.Checked ? (int)ftask.edDays.Value : -1, ftask.edNote.Text, ftask.edCategory.Text);
                m_Tasks.Add(tsk);
                lbTasks.Items.Add(tsk.Name);

                if (cachedTasks.IndexOf(ftask.edTask.Text) == -1)
                {
                    cachedTasks.Insert(0, ftask.edTask.Text);
                    if (cachedTasks.Count == cachedTasksLimit)
                    {
                        cachedTasks.RemoveAt(cachedTasks.Count - 1);
                    }
                }
            }
            RecountSize();
        }

        void lbTasks_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            if (lbTasks.SelectedItem == null)
            {
                return;
            }
            fmTask ftask = new fmTask(false);

            foreach (Task tsk in m_Tasks)
            {
        	    if (tsk.Name.CompareTo(lbTasks.SelectedItem.ToString()) == 0)
        	    {
                    ftask.edTask.Text = tsk.Name;
                    ftask.cbPriority.Checked = tsk.HightPriority;
                    ftask.edDays.Text = tsk.DaysToEnd.ToString();
                    ftask.cbDays.Checked = int.Parse(ftask.edDays.Text) >= 0;
                    ftask.edDays.Enabled = ftask.cbDays.Checked;
                    ftask.edNote.Text = tsk.Note.ToString();
                    ftask.edCategory.Text = tsk.Category.ToString();
                    foreach (String str in cachedTasks)
                    {
                        ftask.cbTasks.Items.Add(str);
                    }
                    ftask.ShowDialog();
                    if (ftask.DialogResult == DialogResult.OK)
                    {
                        lbTasks.Items.Clear();
                        tsk.Name = ftask.edTask.Text;
                        if (cachedTasks.IndexOf(tsk.Name) == -1)
                        {
                            cachedTasks.Insert(0, tsk.Name);
                            if (cachedTasks.Count == cachedTasksLimit)
                            {
                                cachedTasks.RemoveAt(cachedTasks.Count - 1);
                            }
                        }
                        tsk.HightPriority = ftask.cbPriority.Checked;
                        if (ftask.cbDays.Checked)
                        {
                            tsk.DaysToEnd = int.Parse(ftask.edDays.Text);
                        }
                        else
                        {
                            tsk.DaysToEnd = -1;
                        }
                        tsk.Note = ftask.edNote.Text;
                        tsk.Category = ftask.edCategory.Text;
                        foreach (Task item in m_Tasks)
                        {
                            lbTasks.Items.Add(item.Name);
                        }
                    }
                    else if (ftask.DialogResult == DialogResult.Abort)
                    {
                        m_Tasks.RemoveAt(m_Tasks.IndexOf(tsk));
                        lbTasks.Items.Remove(lbTasks.SelectedItem);
                    }
                    break;
        	    }
            }
            RecountSize();
        }

        void fmSender_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (cachedTasks.Count == 0)
            {
                return;
            }
            String tasks = "";
            TextWriter writer = new StreamWriter(@"\SMSTaskerHistory.dat");
            foreach (String str in cachedTasks)
            {
                tasks += str + ";";
            }

            writer.Write(tasks);
            writer.Close();
        }

        void fmSender_Load(object sender, System.EventArgs e)
        {
            TextReader stream = null;
            try
            {
                stream = new StreamReader(@"\SMSTaskerHistory.dat");
            }
            catch
            {
                return;
            }
            String buff = stream.ReadToEnd();

            foreach (String str in buff.Split(';'))
            {
                if (str.Length > 0)
                {
                    if (cachedTasks.Count == cachedTasksLimit)
                    {
                        break;
                    }
                    cachedTasks.Add(str);
                }
            }
            
            stream.Close();
        }

        private void menuItem4_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        private void Send_Click(object sender, EventArgs e)
        {
            //Отправка СМС
            Cursor.Current = Cursors.WaitCursor;
            if (textBox1.Text.Length == 0 || m_Tasks.Count == 0)
            {
                Cursor.Current = Cursors.Default;
                return;
            }
            String message = "*";
            foreach (Task tsk in m_Tasks)
            {
                String taskStr = "";
                if (tsk.HightPriority)
                {
                    taskStr += "!";
                }
                if (tsk.DaysToEnd >= 0)
                {
                    taskStr += "+"+tsk.DaysToEnd.ToString();
                }
                if (tsk.Category.Length >0)
                {
                    taskStr += "$" + tsk.Category;
                }
                if (tsk.Note.Length > 0)
                {
                    taskStr += "#" + tsk.Note;
                }
                taskStr += (taskStr.Length > 0 ? "\\" : "") +tsk.Name;
                message += taskStr+".";
            }
            if (message[message.Length - 1] == '.')
            {
                message = message.Substring(0, message.Length - 1);
            }
            try
            {
                ASCIIEncoding enc = new ASCIIEncoding();

                SmsMessage sms = new SmsMessage(ContactPhone, message);
                sms.Send();
            }
            catch
            {
                MessageBox.Show("Произошла ощибка при отправке SMS.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                Cursor.Current = Cursors.Default;
                return;
            }
            DialogResult = DialogResult.OK;
            Cursor.Current = Cursors.Default;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ChooseContactDialog dial = new ChooseContactDialog();
            dial.ChooseContactOnly = true;
            if (dial.ShowDialog() == DialogResult.OK)
            {
                dial.ChoosePropertyOnly = true;
                dial.RequiredProperties = new ContactProperty[] { ContactProperty.AllPhone };
                dial.ShowDialog();
                if (dial.SelectedPropertyValue != null)
                {
                    ContactName = dial.SelectedContact.FileAs;
                    ContactPhone = dial.SelectedPropertyValue;
                    textBox1.Text = ContactName;
                }
            }
        }

        private void RecountSize()
        {
            String message = "";
            int smsSize = 0;
            if (m_Tasks.Count > 0)
            {
                message = "*";
            }
            foreach (Task tsk in m_Tasks)
            {
                String taskStr = "";
                if (tsk.HightPriority)
                {
                    taskStr += "!";
                }
                if (tsk.DaysToEnd >= 0)
                {
                    taskStr += "+" + tsk.DaysToEnd.ToString();
                }
                if (tsk.Category.Length > 0)
                {
                    taskStr += "$" + tsk.Category;
                }
                if (tsk.Note.Length > 0)
                {
                    taskStr += "#" + tsk.Note;
                }
                taskStr += (taskStr.Length > 0 ? "\\" : "") + tsk.Name;
                message += taskStr + ".";
            }
            if (message.Length > 0 && message[message.Length - 1] == '.')
            {
                message = message.Substring(0, message.Length - 1);
            }
            UTF8Encoding utf8 = new UTF8Encoding();
            smsSize = utf8.GetByteCount(message); ;
            if (smsSize > 160)
            {
                lbSize.ForeColor = Color.Red;
            }
            else
            {
                lbSize.ForeColor = Color.Black;
            }
            lbSize.Text = smsSize.ToString();
        }
    }

    public class Task
    {
        public String Name;
        public String Note;
        public String Category;
        public bool HightPriority;
        public int DaysToEnd;

        public Task(String name, bool hightPriority, int daysToEnd, String note, String category)
        {
            Name = name;
            HightPriority = hightPriority;
            DaysToEnd = daysToEnd;
            Note = note;
            Category = category;
        }
    }
}